package org.lilred.nzbberry.http;

import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.InputConnection;

import org.lilred.nzbberry.download.NzbSwapper;

import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.browser.field2.BrowserFieldConnectionManager;
import net.rim.device.api.browser.field2.BrowserFieldRequest;
import net.rim.device.api.io.http.HttpHeaders;
import net.rim.device.api.ui.UiApplication;

public class ConnectionManager implements BrowserFieldConnectionManager {
	private URL url;
	BrowserField bf;
	HttpConnection connection;
	public ConnectionManager(BrowserField bf) {
		this.bf = bf;
	}
	String[] directDomains = { ".newzbin.com", ".newzxxx.com", ".nzbmatrix.com" };
	public InputConnection makeRequest(BrowserFieldRequest request)	throws Exception {
		url = new URL(request.getURL());
		connection = (HttpConnection) Connector.open(request.getURL() + HttpRequestDispatcher.getConnectionParameters());
		HttpHeaders headers = request.getHeaders();
		for (int i = 0; i < headers.size(); i++) {
			String key = headers.getPropertyKey(i);
			String value = headers.getPropertyValue(i);
			connection.setRequestProperty(key, value);
		}
        if (request.getPostData() != null) {
        	connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            OutputStream requestOutput = connection.openOutputStream();
            requestOutput.write(request.getPostData());
            requestOutput.close();
        }
        bf.getCookieManager().addCookiesToRequest(request.getURL(), connection);
		String disposition = connection.getHeaderField("content-disposition");
		if (disposition != null && disposition.indexOf(".nzb") > 0) {
			UiApplication.getUiApplication().invokeLater(new Runnable() {
				public void run() {
					NzbSwapper swapper = new NzbSwapper(connection);
					swapper.start();
					//Eventually we will add the ability to send links directly to sabnzbd.
					//String domain = url.getGenericDomain();
				}
			});
		}
		int headerNum = 0;
		String headerKey = null;
		String headerValue = null;
		while ((headerKey = connection.getHeaderFieldKey(headerNum)) != null) {
			if (headerKey.toLowerCase().equals("set-cookie") || (headerKey.toLowerCase().equals("set-cookie2"))) {
				headerValue = connection.getHeaderField(headerNum);
				bf.getCookieManager().setCookie(connection.getURL(), headerValue);
			}
			headerNum++;
		}
		return connection;
	}
}
